import { dataSource } from "../../db/typeorm";
import { validatorData } from "../../db/utils";
import { Task, TaskRemark, TaskUser } from "../../entity/task";
import { formatPage, formatPageFileterData } from "../../utils/pages";

// 指定用户下的任务分页列表
export async function taskPage(
  query: { [key: string]: any } & { pageIndex: number; pageSize: number },
  { user_id }: { user_id?: string | number },
) {
  const { pageIndex, pageSize } = formatPage(query);
  const querySql = dataSource
    .getRepository(Task)
    .createQueryBuilder("task")
    .select([
      "task.task_id",
      "task.task_name",
      "task.task_category",
      "task.task_status",
      "task.task_type",
      "task.create_time",
      "user.user_id",
      "user.user_name",
    ])
    .leftJoin("task.create_user_info", "user")
    .leftJoinAndSelect("task.taskUsers", "taskUsers")
    .where("task.create_user = :user_id OR taskUsers.user_id = :user_id", {
      user_id,
    })
    .orderBy("task.create_time", "DESC")
    .take(pageSize)
    .skip((pageIndex - 1) * pageSize);

  const records = await querySql.getMany(); // 获取查询结果
  const total = await querySql.getCount(); // 获取符合条件的数据总数

  return { total, records };
}

// 创建任务
export async function taskCreate(data: any, user_id: number | string) {
  const taskInfo = formatPageFileterData(data, [
    "task_name",
    "task_status",
    "task_type",
    "task_content",
    "task_category",
  ]) as unknown as Task;
  taskInfo.create_user = Number(user_id);
  await validatorData(taskInfo, Task);

  await dataSource.transaction(async (transactionalEntityManager) => {
    const result = await transactionalEntityManager
      .getRepository(Task)
      .insert(taskInfo);
    // 更新中间表
    if (data.task_performer) {
      let performerIds = data.task_performer.split(",") as string[];
      let insertDatas = performerIds.map((item) => ({
        user_id: item,
        task_id: result.raw.insertId,
      }));
      await transactionalEntityManager
        .getRepository(TaskUser)
        .insert(insertDatas);
    }
  });
}

// 修改任务
export async function taskUpdate(data: any, user_id: number | string) {
  if (!data.task_id) {
    throw new Error("任务ID不能为空！");
  }

  const taskInfo = formatPageFileterData(data, [
    "task_id",
    "task_name",
    "task_status",
    "task_type",
    "task_content",
    "task_category",
  ]) as unknown as Task;
  taskInfo.create_user = Number(user_id);
  await validatorData(taskInfo, Task);

  await dataSource.transaction(async (transactionalEntityManager) => {
    // 删除中间表
    await transactionalEntityManager.getRepository(TaskUser).delete({
      task_id: taskInfo.task_id,
    });
    // 修改任务
    await transactionalEntityManager.getRepository(Task).update(
      {
        task_id: taskInfo.task_id,
      },
      taskInfo,
    );
    // 更新中间表
    if (data.task_performer) {
      let performerIds = data.task_performer.split(",") as string[];
      let insertDatas = performerIds.map((item) => ({
        user_id: item,
        task_id: taskInfo.task_id,
      }));
      await transactionalEntityManager
        .getRepository(TaskUser)
        .insert(insertDatas);
    }
  });
}

// 任务详情
export async function taskDetail(task_id: number, user_id: number) {
  if (!task_id) {
    throw new Error("任务ID不能为空！");
  }

  return await dataSource
    .getRepository(Task)
    .createQueryBuilder("task")
    .select([
      "task.task_id",
      "task.task_status",
      "task.task_name",
      "task.create_time",
      "task.task_type",
      "task.task_content",
      "task.task_category",
      "user.user_name",
      "user.user_nick",
    ])
    .leftJoin("task.create_user_info", "user")
    .where("task.task_id = :taskId", { taskId: task_id })
    .getOne();
}

// 任务删除
export async function taskDelete(task_id: number, user_id: number) {
  // 删除任务
  await dataSource.getRepository(Task).delete(task_id);
  // 附件
  // 删除备注
  await dataSource.getRepository(TaskRemark).delete({
    task_id,
  });
  // 删除任务执行者
  await dataSource.getRepository(TaskUser).delete({
    task_id,
  });
}

// 获取任务备注列表
export async function taskRemarks(task_id: number, user_id: number) {
  const result = await dataSource
    .getRepository(TaskRemark)
    .createQueryBuilder("task_remark")
    .select([
      "task_remark.task_id",
      "task_remark.remark_id",
      "task_remark.remark_content",
      "task_remark.create_time",
      "user.user_name",
      "user.user_nick",
    ])
    .leftJoin("task_remark.create_user_info", "user")
    .where("task_remark.task_id = :task_id", {
      task_id,
    })
    .orderBy("task_remark.create_time", "DESC")
    .getMany();
  return result;
}

// 添加任务备注
export async function taskRemarkCreate(data: any, user_id: number) {
  const remarkInfo = formatPageFileterData(data, [
    "task_id",
    "remark_content",
  ]) as unknown as TaskRemark;
  remarkInfo.create_user = Number(user_id);
  await validatorData(remarkInfo, TaskRemark);

  await dataSource.getRepository(TaskRemark).insert(remarkInfo);
}

// 修改任务备注
export async function taskRemarkUpdate(data: any, user_id: number) {
  if (!data.remark_id) {
    throw new Error("任务备注ID不能为空！");
  }

  const remarkInfo = formatPageFileterData(data, [
    "remark_id",
    "task_id",
    "remark_content",
  ]) as unknown as TaskRemark;
  remarkInfo.create_user = Number(user_id);
  await validatorData(remarkInfo, TaskRemark);
  delete remarkInfo.task_id;
  await dataSource.getRepository(TaskRemark).update(
    {
      remark_id: remarkInfo.remark_id,
    },
    remarkInfo,
  );
}

// 删除任务备注
export async function taskRemarkDelete(remark_id: number, user_id: number) {
  await dataSource.getRepository(TaskRemark).delete(remark_id);
}
